import os

from django.db import utils
from rest_framework.decorators import api_view
from . models import Accountmanage,Customer,Saler
from .serializers import CustomerSerializer,SalerSerializer
from django.http import HttpResponse
from collections import namedtuple
from rest_framework.response import Response
from rest_framework import status
import  time
from django.core import signing
import hashlib
from  django.core.cache import cache
import json
from dwebsocket.decorators import accept_websocket

HEADER  = {'typ':'JWP','alg':'default'}
KEY     = 'ShihShaw'
SALT    = 'www.pornhub.com'
TIME_OUT= 60*60

def encrypt(obj):
    """加密"""
    value = signing.dumps(obj, key=KEY, salt=SALT)
    value = signing.b64_encode(value.encode()).decode()
    return value


def decrypt(src):
    """解密"""
    src = signing.b64_decode(src.encode()).decode()
    raw = signing.loads(src, key=KEY, salt=SALT)
    print(type(raw))
    return raw


def create_token(username):
    """生成token信息"""
    # 1. 加密头信息
    header = encrypt(HEADER)
    # 2. 构造Payload
    payload = {"username": username, "iat": time.time()}
    payload = encrypt(payload)
    # 3. 生成签名
    md5 = hashlib.md5()
    md5.update(("%s.%s" % (header, payload)).encode())
    signature = md5.hexdigest()
    token = "%s.%s.%s" % (header, payload, signature)
    # 存储到缓存中
    cache.set(username, token, TIME_OUT)
    return token

def get_payload(token):
    payload = str(token).split('.')[1]
    payload = decrypt(payload)
    return payload


# 通过token获取用户名
def get_username(token):
    payload = get_payload(token)
    return payload['username']
    pass

def get_userrole(account1):
    role = Accountmanage.objects.get(account = account1)
    # print(role.identify)
    return role.identify

def check_token(token):
    username = get_username(token)
    last_token = cache.get(username)
    if last_token:
        return last_token == token
    return False

#将Json格式的数据转化成Object
def UnJson(jsonData):
    json_str = json.dumps(jsonData)
    data = json.loads(json_str, object_hook=lambda d: namedtuple('data', d.keys())(*d.values()))
    return data


@api_view(['POST'])
def LoginIn(request):
    data = UnJson(request.data)
    print(data)
    try:
        user = Accountmanage.objects.filter(account=data.account, upassword=data.password)
        if user:
            data = {'code':200,'token':create_token(data.account),'message':'sendsuceed','role':user[0].identify,'account':user[0].account}
            response = HttpResponse(json.dumps(data))
            # response.set_cookie("token", create_token(data.account), 1800)
            response.status_code = 200
            print(response)
            return response
    except IOError:
        print('2333')
    else:
        data = {'code': 403,  'message': '用户名或密码错误'}
        response = HttpResponse(json.dumps(data))
        print('用户名或密码错误')
        return response

@api_view(['POST'])
def Check(request):
    data = UnJson(request.data)
    if check_token(data.token):
        account = get_username(data.token)
        role = get_username(data.token)
        #这里开始写你的功能
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


#用户注册
@api_view(['POST'])
def UserSignUp(request):
    data = UnJson(request.data)
    try:
        a = Accountmanage.objects.create(account=data.customeraccount, upassword=data.password, identify='customer')
        Customer.objects.create(customeraccount=a,customername=data.customername,address=data.address,phone=data.phone,balance=0)
        data = {'code': 200, 'message': '注册成功'}
        return HttpResponse(json.dumps(data))
    except utils.IntegrityError:
        data = {'code': 403, 'message': '该手机号已被注册'}
        return HttpResponse(json.dumps(data))


@api_view(['POST'])
def SalerSignUp(request):
    data = UnJson(request.data)
    try:
        a = Accountmanage.objects.create(account=data.saleraccount, upassword=data.password, identify='saler')
        Saler.objects.create(saleraccount=a, storename=data.storename, address=data.address,
                                phone=data.phone, balance=0,score=5)
        data = {'code': 200, 'message': '注册成功'}
        return HttpResponse(json.dumps(data))
    except utils.IntegrityError:
        print('5555')
        data = {'code': 403, 'message': '该手机号已被注册'}
        return HttpResponse(json.dumps(data))

    # return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
def UserUpdate(request):
    data = UnJson(request.data)
    if check_token(data.token):
        account = get_username(data.token)
        role = get_username(data.token)
        Customer.objects.filter(pk=account).update(customername=data.customername, address=data.address,
                                                phone=data.phone)
        data = {'code': 200, 'message': '修改成功'}
        return HttpResponse(json.dumps(data))
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))

@api_view(['POST'])
def SalerUpdate(request):
    data = UnJson(request.data)
    if check_token(data.token):
        account = get_username(data.token)
        role = get_username(data.token)
        Saler.objects.filter(pk=account).update(storename=data.storename, address=data.address,
                                                          phone=data.phone)
        data = {'code': 200, 'message': '修改成功'}
        return HttpResponse(json.dumps(data))
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))

@api_view(['POST'])
def GetInformation(request):
    data = UnJson(request.data)
    if check_token(data.token):
        account = get_username(data.token)
        role = get_userrole(account)
        # 这里开始写你的功能
        print(role)
        if(role == 'customer'):
            obj = Customer.objects.get(pk = account)
            serializer = CustomerSerializer(obj)
            return Response(serializer.data)
        else:
            obj = Saler.objects.get(pk = account)
            serializer = SalerSerializer(obj)
            print(serializer)
            return Response(serializer.data)
            # return HttpResponse('ok')
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))

#websocket 测试
# @accept_websocket
# def path(request):
#     if request.is_websocket():
#         # print('saadffasdfdf')
#         request.websocket.send('你可真是个大傻子'.encode('utf-8'))
#         time.sleep(5)
#         request.websocket.send('我让你走了吗？'.encode('utf-8'))

@api_view(['GET'])
def img(request,filename):
    image_data = open('img/'+filename, "rb").read()
    print(type(image_data))
    return HttpResponse(image_data)
    # print(filename)
